//
//  MianViewController.m
//  QRMaster
//
//  Created by liuyunlong on 15/11/10.
//  Copyright © 2015年 myApple. All rights reserved.
//

#import "MianViewController.h"
#import "GenerateCardViewController.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "MJRefresh.h"
#import "OpertionPlist.h"
#import "CardInfoModel.h"
#import "CardInfoTableViewCell.h"
#import "SelectRoomViewController.h"
#import "BulidingModel.h"
#import "FloorsModel.h"
#import "roomsModel.h"
#import "faveriterCard.h"
#import "BackTableViewCell.h"
#import "RoomTimeController.h"
#import "StartPageController.h"
#import "checkPower.h"
#import "BulidingInfoLogic.h"
#import "FloorsInfoLogic.h"
#import "RoomInfoLogic.h"
#import "QRSingleton.h"
#import "MJExtension.h"
#import "ChineseInclude.h"
#import "ZYPinYinSearch.h"
#import "FunctionViewController.h"

@interface MianViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UIGestureRecognizerDelegate,CardInfoTableViewCellDelegate,UISearchBarDelegate>
{
    NSString * communityId;
    NSString * bulidingName;
    NSString * floorName;
    UISearchBar * nameSearchBar;
    UIButton * nameSearchBtn;
    UIButton * changeCommunityBtn;
    UIImageView * searchImgView;
    UIImageView * cancelImgView;//取消搜索
    QRSingleton * singleton;
    NSMutableArray * cardInfoMutArray;
    NSMutableArray * totalArray;//总数据
    
    UITableView * cardInfoTableView;
    
    NSString * bulidingId;
    NSString * floorId;
    
    NSUserDefaults * userInfo;
    
    UIImageView * promtBackImgView;//没有房间的提示页面
    
    NSMutableArray * faveriteRoomIdArray;
    
    UILabel * communityNameLabel;
    UIView * nameLabelView;
    
    UIView * allBackImgView;//点击+号的遮盖的背景
    UITableView * backTabelView;//点击＋出现的黑色view
    NSArray * backChooseArray;
    NSArray * backChooseImgArray;
    CGRect backTabelViewFrame;
    NSInteger panCount;
    UIView * swipeView;
    UILabel * promtLabel;
    UILabel * promtLabelRefresh;
    NSString * communityRole;
    UILabel * cancelSearchLabel;
    BOOL haveCommunityFlag;//是否有集群
    BOOL comeFlag;//no切换页面过来 yes选择楼层过来的
}

@end

@implementation MianViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        faveriteRoomIdArray = [[NSMutableArray alloc]init];
        backChooseImgArray = @[@"ic_change20",@"ic_eye20",@"functionCard"];
        panCount = 0;
        floorId = @"";
        bulidingId = @"";
        comeFlag = NO;
        singleton = [QRSingleton sharedQRSingleton];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"锁掌柜";
    cardInfoMutArray = [[NSMutableArray alloc]init];
    totalArray = [[NSMutableArray alloc]init];
    userInfo = [NSUserDefaults standardUserDefaults];
    backChooseArray = @[NSLocalizedString(@"changefloor", nil),NSLocalizedString(@"showCommunity", nil),NSLocalizedString(@"functionCard", nil)];
    haveCommunityFlag = NO;
    [self PrepareTitelView];
    [self prepareCommunityData];
    [self prepareTableView];
    [self prepareBtnView];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationItem.title = NSLocalizedString(@"card", nil);
    nameSearchBtn.hidden = NO;
    changeCommunityBtn.hidden = NO;
    panCount = 0;
    if (![communityId isEqualToString:singleton.communityId] || communityId == nil)
    {
        communityId = singleton.communityId;
        if (!comeFlag) {
            bulidingId = @"";
            floorId = @"";
            comeFlag = NO;
        }
        [self getDataFromDisk];
        [self prepareCommunity];
    }
    else
    {
        [self getDataFromDisk];
    }
    backChooseArray = @[NSLocalizedString(@"changefloor", nil),NSLocalizedString(@"showCommunity", nil),NSLocalizedString(@"functionCard", nil)];
    promtLabel.text = NSLocalizedString(@"addCommunityRefresh", nil);
    promtLabelRefresh.text = NSLocalizedString(@"refreshRoom", nil);
    nameSearchBar.placeholder = NSLocalizedString(@"roomNo", nil);
    cancelSearchLabel.text = NSLocalizedString(@"alterCancel", nil);
    [backTabelView reloadData];
    [cardInfoTableView reloadData];
    self.navigationItem.title = NSLocalizedString(@"card", nil);
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    nameSearchBtn.hidden = YES;
    nameSearchBar.hidden = YES;
    nameSearchBar.text = @"";
    changeCommunityBtn.hidden = YES;
    cancelImgView.hidden = YES;
}

-(void)PrepareTitelView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float x = ScreenWidth - 40;
    float y = 2;
    float width = 40;
    float height = 40;

    changeCommunityBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    changeCommunityBtn.frame = CGRectMake(x, y, width, height);
    [changeCommunityBtn addTarget:self action:@selector(addClick) forControlEvents:UIControlEventTouchUpInside];
    [changeCommunityBtn setImage: [UIImage imageNamed:@"ic_add30"] forState:0];
    [self.navigationController.navigationBar addSubview:changeCommunityBtn];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 50, ScreenWidth, 1)];
    lineView.backgroundColor = RGBA(237, 238, 241, 1);
    [self.view addSubview:lineView];
    
    x = 0;
    y = 0;
    width = ScreenWidth;
    height = 40;
    nameLabelView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    nameLabelView.backgroundColor = RGBA(255, 255, 204, 1);
    [self.view addSubview:nameLabelView];
    x = 40;
    y = 0;
    width = ScreenWidth - 80;
    communityNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    communityNameLabel.text = NSLocalizedString(@"noCommunity", nil);
    
    communityNameLabel.numberOfLines = 2;
    communityNameLabel.font = [UIFont systemFontOfSize:14.0];
    communityNameLabel.textColor = [UIColor blackColor];
    communityNameLabel.textAlignment = NSTextAlignmentCenter;
    [nameLabelView addSubview:communityNameLabel];
    
    x = ScreenWidth - 40;
    y = 0;
    width = 40;
    height = 40;
    UIButton * communityNameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    communityNameBtn.frame = CGRectMake(x, y, width, height);
    [communityNameBtn setImage:[UIImage imageNamed:@"ic_close20"] forState:0];
    [communityNameBtn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [nameLabelView addSubview:communityNameBtn];
    
    //搜索
    x = ScreenWidth - 80;
    y = 2;
    height = 40;
    width = 40;
    nameSearchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nameSearchBtn.frame = CGRectMake(x, y, width, height);
    [nameSearchBtn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:nameSearchBtn];
    
    searchImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 10, 20, 20)];
    searchImgView.image = [UIImage imageNamed:@"ic_search"];
    [nameSearchBtn addSubview:searchImgView];
    
    nameSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth - 60, 44)];
    nameSearchBar.hidden = YES;
    nameSearchBar.delegate = self;
    nameSearchBar.placeholder = NSLocalizedString(@"roomNo", nil);
    nameSearchBar.backgroundColor = RGBA(192, 191, 196, 1);
    [self.navigationController.navigationBar addSubview:nameSearchBar];
    
    x = ScreenWidth - 60;
    width = 60;
    height = 44;
    y = 0;
    cancelImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    cancelImgView.userInteractionEnabled = YES;
    cancelImgView.hidden = YES;
    cancelImgView.backgroundColor = RGBA(192, 191, 196, 1);
    [self.navigationController.navigationBar addSubview:cancelImgView];
    
    x = 0;
    y = 12;
    width = 60;
    height = 20;
    cancelSearchLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    cancelSearchLabel.text = NSLocalizedString(@"alterCancel", nil);
    cancelSearchLabel.font = [UIFont systemFontOfSize:16.0];
    cancelSearchLabel.textAlignment = NSTextAlignmentCenter;
    [cancelImgView addSubview:cancelSearchLabel];
    
    UITapGestureRecognizer * cancelSearchTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelSearchClick)];
    [cancelImgView addGestureRecognizer:cancelSearchTap];
    
}

-(void)searchClick
{
//    [self addClick];
    nameSearchBar.hidden = NO;
    cancelImgView.hidden = NO;
    self.navigationItem.title = @"";
}

-(void)cancelSearchClick
{
    nameSearchBar.hidden = YES;
    cancelImgView.hidden = YES;
    nameSearchBar.text = @"";
    self.navigationItem.title = NSLocalizedString(@"card", nil);
    cardInfoMutArray = [totalArray mutableCopy];
    [cardInfoTableView reloadData];
    [nameSearchBar resignFirstResponder];
}

#pragma mark -- searchDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [cardInfoMutArray removeAllObjects];
    if (![ChineseInclude isIncludeChineseInString:searchBar.text])
    {
        cardInfoMutArray = [NSMutableArray arrayWithArray: [ZYPinYinSearch searchWithOriginalArray:totalArray andSearchText:searchBar.text andSearchByPropertyName:@"roomName"]];
//        for (CardInfoModel * model in totalArray) {
//            if (([model.roomName rangeOfString:searchBar.text].location != NSNotFound))
//            {
//                [cardInfoMutArray addObject:model];
//                [cardInfoTableView reloadData];
//            }
//        }
         [cardInfoTableView reloadData];

    }else
    {
    
        for (CardInfoModel * model in totalArray) {
            if (([model.roomName rangeOfString:searchBar.text].location != NSNotFound))
            {
                [cardInfoMutArray addObject:model];
                [cardInfoTableView reloadData];
            }
        }
    }
    
    if (cardInfoMutArray.count == 0) {
        [PromptInfoView showMessage:NSLocalizedString(@"noSearch", nil)];
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

-(void)cancel
{
    cardInfoMutArray = totalArray;
    nameLabelView.hidden = YES;
    cardInfoTableView.frame = CGRectMake(0, 0, cardInfoTableView.frame.size.width, UI_SCREEN_HEIGHT - 64 - 49);
    [cardInfoTableView reloadData];
    [nameSearchBar resignFirstResponder];
}

-(void)prepareBtnView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight;
    allBackImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
    allBackImgView.userInteractionEnabled = YES;
    allBackImgView.hidden = YES;
    [self.view addSubview:allBackImgView];
    UITapGestureRecognizer * tapAllBackView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addClick)];
    tapAllBackView.delegate = self;
    [allBackImgView addGestureRecognizer:tapAllBackView];
    
    x = allBackImgView.frame.size.width - 34;
    y = 2;
    width = 11;
    height = 8;
    UIImageView * triangleView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    triangleView.image = [UIImage imageNamed:@"triangle"];
    triangleView.backgroundColor = [UIColor clearColor];
    [allBackImgView addSubview:triangleView];
    
    x = ScreenWidth - 144;
    y = 10;
    width = 138;
    height = backChooseArray.count * 40;
    backTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    backTabelView.dataSource = self;
    backTabelView.delegate = self;
    backTabelView.bounces = NO;
    backTabelView.layer.cornerRadius = 2;
    backTabelView.layer.masksToBounds = YES;
    backTabelView.userInteractionEnabled = YES;
    backTabelView.separatorStyle = NO;
    [allBackImgView addSubview:backTabelView];
    backTabelViewFrame = backTabelView.frame;
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

#pragma mark -- 点击➕号
-(void)addClick
{
    CGRect replaceRect = backTabelViewFrame;
    if (!allBackImgView.hidden) {
        replaceRect.origin.x = replaceRect.origin.x + 80;
        replaceRect.size.width = replaceRect.size.width / 4.0;
        replaceRect.size.height = 0;
        [UIView animateWithDuration:0.1 animations:^{
            backTabelView.frame = replaceRect;
            backTabelView.alpha = 0;
        } completion:^(BOOL finished)
        {
            backTabelView.frame = backTabelViewFrame;
            allBackImgView.hidden = !allBackImgView.hidden;
        }];
    }
    else
    {
        allBackImgView.hidden = !allBackImgView.hidden;
        backTabelView.alpha = 1;
    }
    
}

#pragma mark -- 获取历史收藏房卡
-(void)getCardInfoByPlist
{
    NSMutableDictionary * dict = [OpertionPlist readDataFromPlist];
    NSMutableArray * cardInfoArray = [dict objectForKey:FAVERITCARD];
    [faveriteRoomIdArray removeAllObjects];
    for (NSDictionary * cardDict in cardInfoArray) {
        NSString * faveriteRoomId = [cardDict objectForKey:@"roomId"];
        [faveriteRoomIdArray addObject:faveriteRoomId];
    }
    
    [cardInfoTableView reloadData];
}

-(void)prepareCommunity
{
    if ([self IsHaveNetwork]) {
        [cardInfoTableView.mj_header endRefreshing];
        return;
    }
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    power.powerBlock = ^(id data,id error)
    {
        if (error != nil)
        {
            if ([[error objectForKey:@"status"]integerValue] == 210)
            {
                NSMutableDictionary * communityData = [[NSMutableDictionary alloc]initWithObjectsAndKeys:nil,COMMUNITYINFOFORKEY,nil];//没有集群的时候
                [OpertionPlist writeDataToPlist:communityData];
                 [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
            else
            {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
        }
        else  if (data != nil)
        {
            NSDictionary * CommunityData = [data objectForKey:@"data"];
            NSArray * communityArr = [CommunityData objectForKey:@"communities"];
            if (communityArr.count > 0) {
                for (NSDictionary * dict in communityArr)
                {
                    if ([[dict objectForKey:@"communityid"]isEqualToString:communityId])
                    {
                        communityRole = [dict objectForKey:@"role"];
                        haveCommunityFlag = YES;
                    }
                }
                if (!haveCommunityFlag) {
                    communityId = [communityArr[0] objectForKey:@"communityid"];
                    communityNameLabel.text=[communityArr[0] objectForKey:@"communityname"];
                    [QRSingleton sharedQRSingleton].communityId = communityId;
                    [QRSingleton sharedQRSingleton].communityName = [communityArr[0] objectForKey:@"communityname"];
                    haveCommunityFlag = NO;
                }
            }
            else
            {
                float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
                float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
                float x = 0;
                float y = 0;
                float width = ScreenWidth;
                float height = ScreenHeight - 49;
                UIImageView * promtBackView = [[UIImageView alloc]initWithFrame:CGRectMake(x,y, width, height)];
                promtBackView.backgroundColor = RGBA(237, 238, 241, 1);
                promtBackView.userInteractionEnabled = YES;
                [self.view addSubview:promtBackView];
                UITapGestureRecognizer * imgViewTap  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backViewClick:)];
                [promtBackView addGestureRecognizer:imgViewTap];
                
                x = 0;
                width = ScreenWidth;
                y = ScreenHeight / 2.0 - 10;
                height = 20;
                promtLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
                promtLabel.text = NSLocalizedString(@"addCommunityRefresh", nil);
                promtLabel.textColor = RGBA(143, 147, 148, 0.5);
                promtLabel.textAlignment = NSTextAlignmentCenter;
                [promtBackView addSubview:promtLabel];
                return;
            }
            [self promtNoRoom];
            [self getCardInfoByPlist];
            [self prepareCommunityData];
        }
        [cardInfoTableView.mj_header endRefreshing];
    };
}


#pragma mark --------功能卡
-(void)promtNoRoom
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - 64 - 49;
    promtBackImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x,y, width, height)];
    promtBackImgView.backgroundColor = RGBA(237, 238, 241, 1);
    promtBackImgView.userInteractionEnabled = NO;
    [cardInfoTableView addSubview:promtBackImgView];
    promtBackImgView.hidden = YES;
    
    x = 0;
    width = ScreenWidth;
    y = ScreenHeight / 2.0 - 10;
    height = 20;
    promtLabelRefresh = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtLabelRefresh.text = NSLocalizedString(@"refreshRoom", nil);
    promtLabelRefresh.textColor = RGBA(143, 147, 148, 0.5);
    promtLabelRefresh.textAlignment = NSTextAlignmentCenter;
    [promtBackImgView addSubview:promtLabelRefresh];
}


-(void)backViewClick:(UITapGestureRecognizer *)tap
{
    [self prepareCommunityData];
}

-(void)getDataFromDisk
{
    [cardInfoMutArray removeAllObjects];
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    [bulidingDataBase queryBulidingInfo:communityId block:^(NSMutableArray *bulidingArray)
     {
         if ([bulidingId isEqualToString:@""] && bulidingArray.count > 0 )
         {
             BulidingModel * model = bulidingArray[0];
             bulidingId = model.buildingId;
             bulidingName = model.buildingName;
         }
         else
         {
             bulidingName = @"";
             floorName = @"";
             for (BulidingModel * model in bulidingArray)
             {
                 if ([model.buildingId isEqualToString:bulidingId])
                 {
                     bulidingName = model.buildingName;
                 }
                 
             }
             if ([bulidingName isEqualToString:@""]) {
                 bulidingId = @"";
                 floorId = @"";
             }
         }
         
     }];
    
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    [floorDataBase queryFloorsInfo:bulidingId block:^(NSMutableArray *arr)
     {
         if ([floorId isEqualToString:@""] && arr.count > 0 ) {
             FloorsModel * model = arr[0];
             floorId = model.floorId;
             floorName = model.floorName;
         }
         else
         {
             floorName = @"";
             for (FloorsModel * floorModel in arr)
             {
                 if ([floorModel.floorId isEqualToString:floorId])
                 {
                     floorName = floorModel.floorName;
                 }
             }
             if ([floorName isEqualToString:@""]) {
                   floorId = @"";
             }
         }
     }];
    
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    [roomDataBase queryRoomInfo:floorId block:^(NSMutableArray * roomResultArray)
     {
         for (RoomsModel * model in roomResultArray)
         {
             CardInfoModel * cardModel = [[CardInfoModel alloc]init];
             cardModel.bulidingId = bulidingId;
             cardModel.bulidingName = bulidingName;
             cardModel.floorId = floorId;
             cardModel.floorName = floorName;
             cardModel.roomId = model.roomId;
             cardModel.roomName = model.roomName;
             [cardInfoMutArray addObject:cardModel];
         }
     }];
    totalArray = [cardInfoMutArray mutableCopy];
    communityNameLabel.text = [NSString stringWithFormat:@"%@%@%@",singleton.communityName,bulidingName,floorName];
    [self getCardInfoByPlist];
}

-(void)insertDataIntoRooms:(NSArray *)allBuildingInfo
{
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    for (NSDictionary * bDict in allBuildingInfo)
    {
        BulidingModel * bModel = [[BulidingModel alloc]init];
        bModel.buildingName = [bDict objectForKey:@"buildingname"];
        bModel.buildingId = [bDict objectForKey:@"buildingid"];
        bModel.buildingNo = [bDict objectForKey:@"buildingno"];
        [bulidingDataBase insertBulidingInfo:bModel withCommunityId:communityId];
        bModel.floors = [bDict objectForKey:@"floors"];
        for (NSDictionary * fDict in bModel.floors) {
            FloorsModel * fModel = [[FloorsModel alloc]init];
            fModel.floorId = [fDict objectForKey:@"floorid"];
            fModel.floorName = [fDict objectForKey:@"floorname"];
            fModel.floorNo  = [fDict objectForKey:@"floorno"];
            [floorDataBase insertFloorInfo:fModel withCommunityId:communityId buildingId:bModel.buildingId];
            fModel.rooms = [fDict objectForKey:@"rooms"];
            for (NSDictionary * rDict in fModel.rooms) {
                RoomsModel * rModel = [[RoomsModel alloc]init];
                rModel.roomId = [rDict objectForKey:@"roomid"];
                rModel.roomName = [rDict objectForKey:@"roomname"];
                rModel.roomNo = [rDict objectForKey:@"roomno"];
                rModel.isSelect = [rDict objectForKey:@"isSelected"];
                rModel.lockNo = [rDict objectForKey:@"lockno"];
                rModel.occupation = [rDict objectForKey:@"occupation"];
                [roomDataBase insertRoomInfo:rModel withFloorId:fModel.floorId withCommunityId:communityId];
            }
        }
    }
}

-(void)prepareCommunityData
{
    if ([self IsHaveNetwork]) {
        [cardInfoTableView.mj_header endRefreshing];
        return;
    }
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:communityId forKey:@"communityId"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
//    if([self getTimestamp:communityId timeKey:@"room_timestamp"] != nil)
//    {
//        [postDict setValue:[self getTimestamp:communityId timeKey:@"room_timestamp"] forKey:@"timestamp"];
//    }
//    else
//    {
//        [postDict setValue:@"" forKey:@"timestamp"];
//    }
    __weak MianViewController * weakSelf = self;
    [self startWaiting:nil color:nil addToView:self.view];
    [rnk initWithPath:POST(HOTELINFO) params:postDict block:^(id downLoadData, id error)
     {
        [self stopWaiting];
         NSLog(@"数据=%@",downLoadData);
        NSDictionary * cache = [downLoadData objectForKey:@"cache"];
        NSArray * data = [downLoadData objectForKey:@"data"];
        if(cache != nil)
        {
            [self updateTimestamp:communityId timeKey:@"room_timestamp" timeKeyValue:[cache objectForKey:@"timestamp"]];
            if([@"1" isEqualToString:[NSString stringWithFormat:@"%@",[cache objectForKey:@"status"]]]==YES)
            {
                if (data != nil)
                {
                    [cardInfoMutArray removeAllObjects];
                    NSArray * cardInfoArray = data;
//                    haveControlFlag=NO;
                    if (cardInfoArray.count > 0)
                    {
                        [self deleteRooms];
                        [weakSelf insertDataIntoRooms:cardInfoArray];
                        [weakSelf analysisHouseData:cardInfoArray];
                    NSMutableDictionary * dict = [OpertionPlist readDataFromPlist];
                    [dict setValue:data forKey:HOUSEINFO];
                    [OpertionPlist writeDataToPlist:dict];
                }
                
            }
                communityNameLabel.text = [NSString stringWithFormat:@"%@%@%@",singleton.communityName,bulidingName,floorName];
            }
            
        }
        else if (error != nil)
        {
            if ([[error objectForKey:@"status"]intValue] == 211)
            {
                [PromptInfoView showMessage:NSLocalizedString(@"addCommunity", nil)];
            }
            else if([[error objectForKey:@"status"]intValue] != 301)
            {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
               
            }
            if ([[error objectForKey:@"status"]intValue] == 301) {
                [self deleteRooms];
                communityNameLabel.text = singleton.communityName;
                [cardInfoMutArray removeAllObjects];
            }
            NSMutableDictionary * dict = [OpertionPlist readDataFromPlist];
            [dict setValue:data forKey:HOUSEINFO];
            [OpertionPlist writeDataToPlist:dict];
            NSLog(@"数据错误error = %@",error);
        }
         if (cardInfoMutArray.count == 0)
         {
             [PromptInfoView showMessage:NSLocalizedString(@"noRoomInfo", nil)];
         }

        totalArray = [cardInfoMutArray mutableCopy];
        [cardInfoTableView reloadData];
        [cardInfoTableView.mj_header endRefreshing];
    }];
}

-(void)deleteRooms
{
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    [bulidingDataBase deleteBulidingWithCommunityId:communityId];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    [floorDataBase deleteFloorsInfoWithCommunityId:communityId];
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    [roomDataBase deleteRoomWithCommunityId:communityId];
    bulidingId = @"";
    bulidingName = nil;
    floorId = @"";
    floorName = nil;
}

-(void)analysisHouseData:(NSArray *)data
{
    if (data.count > 0 && [bulidingId isEqualToString:@""])
    {
        BulidingModel * bModel = [[BulidingModel alloc]init];
        NSDictionary * bDict = data[0];
        bModel.buildingId = [bDict objectForKey:@"buildingid"];
        bModel.buildingName = [bDict objectForKey:@"buildingname"];
        bModel.floors = [bDict objectForKey:@"floors"];
        bulidingName = bModel.buildingName;
        bulidingId = bModel.buildingId;
        FloorsModel * fModel = [[FloorsModel alloc]init];
        NSDictionary * fDict = bModel.floors[0];
        fModel.floorId = [fDict objectForKey:@"floorid"];
        fModel.floorName = [fDict objectForKey:@"floorname"];
        fModel.rooms = [fDict objectForKey:@"rooms"];
        floorId = fModel.floorId;
        floorName = fModel.floorName;
        for (NSDictionary * rDict in fModel.rooms) {
            RoomsModel * rModel = [[RoomsModel alloc]init];
            rModel.roomId = [rDict objectForKey:@"roomid"];
            rModel.roomName = [rDict objectForKey:@"roomname"];
            rModel.occupation = [rDict objectForKey:@"occupation"];
            rModel.lockNo = [rDict objectForKey:@"lockNo"];
            rModel.isSelect = [rDict objectForKey:@"isSelect"];
            rModel.roomNo = [rDict objectForKey:@"roomNo"];
            CardInfoModel * cardModel = [[CardInfoModel alloc]init];
            cardModel.bulidingName = bulidingName;
            cardModel.bulidingId = bulidingId;
            cardModel.floorName = floorName;
            cardModel.floorId = floorId;
            cardModel.roomName = rModel.roomName;
            cardModel.roomId = rModel.roomId;
            cardModel.cardStyle = 2;
            [cardInfoMutArray addObject:cardModel];
        }
        
    }
    else if(data.count > 0 && ![bulidingId isEqualToString:@""])
    {
        for (NSDictionary * bDict in data) {
            if ([bulidingId isEqualToString:[bDict objectForKey:@"buildingid"]]) {
                BulidingModel * bModel = [[BulidingModel alloc]init];
                bModel.buildingName = [bDict objectForKey:@"buildingname"];
                bModel.floors = [bDict objectForKey:@"floors"];
                bulidingName = bModel.buildingName;
                for (NSDictionary * fDict in bModel.floors) {
                    if ([floorId isEqualToString:[fDict objectForKey:@"floorid"]]) {
                        FloorsModel * fModel = [[FloorsModel alloc]init];
                        fModel.floorName = [fDict objectForKey:@"floorname"];
                        fModel.rooms = [fDict objectForKey:@"rooms"];
                        floorName = fModel.floorName;
                        for (NSDictionary * rDict in fModel.rooms) {
                            RoomsModel * rModel = [[RoomsModel alloc]init];
                            rModel.roomId = [rDict objectForKey:@"roomid"];
                            rModel.roomName = [rDict objectForKey:@"roomname"];
                            rModel.occupation = [rDict objectForKey:@"occupation"];
                            rModel.lockNo = [rDict objectForKey:@"lockNo"];
                            rModel.isSelect = [rDict objectForKey:@"isSelect"];
                            rModel.roomNo = [rDict objectForKey:@"roomNo"];
                            CardInfoModel * cardModel = [[CardInfoModel alloc]init];
                            cardModel.bulidingName = bulidingName;
                            cardModel.bulidingId = bulidingId;
                            cardModel.floorName = floorName;
                            cardModel.floorId = floorId;
                            cardModel.roomName = rModel.roomName;
                            cardModel.roomId = rModel.roomId;
                            cardModel.cardStyle = 2;
                            [cardInfoMutArray addObject:cardModel];
                        }
                    }
                }
            }
        }
    }
}

-(void)prepareTableView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT - 64 - 49;
    
    cardInfoTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    cardInfoTableView.delegate = self;
    cardInfoTableView.dataSource = self;
    cardInfoTableView.backgroundColor = [UIColor whiteColor];
    cardInfoTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:cardInfoTableView];
    __weak MianViewController * weakSelf = self;
    [cardInfoTableView.mj_header beginRefreshing];
    cardInfoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (nameSearchBar.hidden == NO) {
            [weakSelf cancelSearchClick];
        }
        [weakSelf getCardInfoByPlist];
        [weakSelf prepareCommunity];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == cardInfoTableView) {
        return cardInfoMutArray.count;
    }
    else
        return backChooseArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == cardInfoTableView) {
        return 60;
    }
    else
        return 40;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == cardInfoTableView) {
        NSString * string = @"cell";
        CardInfoTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:string];
        if (!cell) {
            cell = [[CardInfoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
        }
        cell.delegate = self;
        if (cardInfoMutArray.count > indexPath.row) {
            CardInfoModel * model = cardInfoMutArray[indexPath.row];
            cell.cardStyle = model.cardStyle;
            cell.communityid = communityId;
            cell.bulidingId = model.bulidingId;
            cell.bulidingName = model.bulidingName;
            cell.floorId = model.floorId;
            cell.floorName = model.floorName;
            cell.roomId = model.roomId;
            cell.roomName = model.roomName;
            cell.Index = (int)indexPath.row;
            cell.timeImgView.image = [UIImage imageNamed:@"ic_time30"];
            cell.faveritImgView.image = [UIImage imageNamed:@"ic_heart"];
//            cell.reloadView = YES;
            for (NSString * faveriteRoomiD in faveriteRoomIdArray) {
                if ([faveriteRoomiD isEqualToString:model.roomId]) {
                    cell.faveritImgView.image = [UIImage imageNamed:@"ic_heartfilled"];
                }
            }
            
        }
        return cell;
    }
    else
    {
        static NSString * cellString = @"cell";
        BackTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellString];
        if (!cell) {
            cell = [[BackTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellString];
        }
        cell.selectedBackgroundView = [[UIImageView alloc]initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = [UIColor blackColor];
        cell.contentView.backgroundColor = [UIColor blackColor];
        cell.imgString = backChooseImgArray[indexPath.row];
        cell.content = backChooseArray[indexPath.row];
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (panCount > 0) {
        [self retainCell];
        return;
    }
    if (tableView == cardInfoTableView) {
        CardInfoModel * model = [[CardInfoModel alloc]init];
        model = cardInfoMutArray[indexPath.row];
        GenerateCardViewController * gvc = [[GenerateCardViewController alloc]initwithCommuntyId:communityId communityName:singleton.communityName model:model];
        gvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:gvc animated:YES];
        [cardInfoTableView deselectRowAtIndexPath:[cardInfoTableView indexPathForSelectedRow] animated:YES];
    }
    else
    {
        if (indexPath.row == 0) {
            if (communityId) {
                [self changeCommunity];
            }
            else
                [PromptInfoView showMessage:NSLocalizedString(@"noAddCommunity", nil) superView:self.view];
        }
        else if(indexPath.row == 1)
        {
            nameLabelView.hidden = NO;
            cardInfoTableView.frame = CGRectMake(0, 40, cardInfoTableView.frame.size.width, UI_SCREEN_HEIGHT - 64 - 40 - 49);
        }
        else
        {
            FunctionViewController * fvc = [[FunctionViewController alloc]init];
             fvc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:fvc animated:YES];
        }
        [self addClick];
        [backTabelView deselectRowAtIndexPath:[backTabelView indexPathForSelectedRow] animated:YES];
    }
    
}

-(void)retainCell
{
    CGRect frame = swipeView.frame;
    frame.origin.x = 0;
    swipeView.frame = frame;
    [cardInfoTableView reloadData];
    panCount = 0;
}


#pragma mark -- cardInfoTableViewCellDelegate
-(void)sendControllerHavePan:(NSInteger)flag cellView:(UIView *)addView
{
    panCount = flag;
    swipeView = addView;
}

-(void)closeSwipeView
{
    [self retainCell];
}

-(void)sendControllerClickFaverit:(int)cellIndex cardInfoCell:(CardInfoTableViewCell *)clickCell
{
    CardInfoTableViewCell * cell = clickCell;
    NSMutableDictionary * faveritDict = [[NSMutableDictionary alloc]init];
    CardInfoModel * model = cardInfoMutArray[cellIndex];
    [faveritDict setValue:communityId forKey:@"communityId"];
    [faveritDict setValue:singleton.communityName forKey:@"communityName"];
    [faveritDict setValue:model.bulidingId forKey:@"buildId"];
    [faveritDict setValue:model.bulidingName forKey:@"buildName"];
    [faveritDict setValue:model.floorId forKey:@"floorId"];
    [faveritDict setValue:model.floorName forKey:@"floorName"];
    [faveritDict setValue:model.roomId forKey:@"roomId"];
    [faveritDict setValue:model.roomName forKey:@"roomName"];
    [faveriterCard faveriterOrCancelCardByRoomId:faveritDict result:^(cardResultType type) {
        switch (type) {
            case KCSUCCESS_FAVERITER:
                [PromptInfoView showMessage:NSLocalizedString(@"collectCardSuccess", nil)];
                cell.faveritImgView.image = [UIImage imageNamed:@"ic_heartfilled"];
                break;
            case KCFAIL_FAVERITER:
                [PromptInfoView showMessage:NSLocalizedString(@"collectCount", nil)];
                break;
            case KCCANCEL_FAVERITER:
                [PromptInfoView showMessage:NSLocalizedString(@"cancleCardCollect", nil)];
                cell.faveritImgView.image = [UIImage imageNamed:@"ic_heart"];
                break;
        }
        [self getCardInfoByPlist];
        double delayInSeconds = 0.5;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^{
            [self retainCell];
            [cardInfoTableView reloadData];
        });
    }];
    
}

-(void)sendShowTimeClick:(NSString *)roomid
{
    RoomTimeController * rtc = [[RoomTimeController alloc]init];
    rtc.roomId = roomid;
    rtc.communityId = communityId;
    rtc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:rtc animated:YES];
    [self retainCell];
}

#pragma mark -- 点击浮标的时候切换
-(void)changeCommunity
{
    SelectRoomViewController * src = [[SelectRoomViewController alloc]initWith:communityId bulidingId:bulidingId floorid:floorId];
    src.hidesBottomBarWhenPushed = YES;
    src.houseInfo = ^(NSString * comId,NSString * bulidingid,NSString * floorid)
    {
        if (![comId isEqualToString:communityId]) {
            singleton.communityId = comId;
        }
            bulidingId = bulidingid;
            floorId = floorid;
            [cardInfoTableView reloadData];
        comeFlag = YES;
    };
    [self.navigationController pushViewController:src animated:YES];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
